package com.example.treeUtils;

import java.util.ArrayList;
import java.util.List;

import com.example.viewInfo.ChargeTypeTreeView;

public class ChargeTypeTreeUtil {
    /**
     * 两层循环实现建树
     *
     * @param treeNodes 传入的树节点列表
     * @return
     */
    public static List<ChargeTypeTreeView> bulid(List<ChargeTypeTreeView> treeNodes) {

        List<ChargeTypeTreeView> trees = new ArrayList<ChargeTypeTreeView>();

        for (ChargeTypeTreeView treeNode : treeNodes) {

            if (0 == treeNode.getPid()) {
                trees.add(treeNode);
            }

            for (ChargeTypeTreeView it : treeNodes) {
                if (it.getPid() == treeNode.getChargeTypeId()) {
                    if (treeNode.getChildren() == null) {
                        treeNode.setChildren(new ArrayList<ChargeTypeTreeView>());
                    }
                    treeNode.getChildren().add(it);
                }
            }
        }
        return trees;
    }

    /**
     * 使用递归方法建树
     *
     * @param treeNodes
     * @return
     */
    public static List<ChargeTypeTreeView> buildByRecursive(List<ChargeTypeTreeView> treeNodes) {
        List<ChargeTypeTreeView> trees = new ArrayList<ChargeTypeTreeView>();
        for (ChargeTypeTreeView treeNode : treeNodes) {
            if (String.valueOf(treeNode.getPid()).equals("0")) {
                trees.add(findChildren(treeNode, treeNodes));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param treeNodes
     * @return
     */
    public static ChargeTypeTreeView findChildren(ChargeTypeTreeView treeNode, List<ChargeTypeTreeView> treeNodes) {
        treeNode.setChildren(new ArrayList<ChargeTypeTreeView>());

        for (ChargeTypeTreeView it : treeNodes) {
            if (String.valueOf(treeNode.getChargeTypeId()).equals(String.valueOf(it.getPid()))) {
                if (treeNode.getChildren() == null) {
                    treeNode.setChildren(new ArrayList<ChargeTypeTreeView>());
                }
                treeNode.getChildren().add(findChildren(it, treeNodes));
            }
        }
        return treeNode;
    }

}
